# -*- coding: utf-8 -*-
import datetime
import logging
import re
from tvdb_api import Tvdb, tvdb_shownotfound

from nmj.abstract import TVShowScanner, NMJTVShow, TVShowSearchResult, \
	NMJTVMediaInfo, NMJTVShowSeason, NMJTVShowEpisode, NMJPerson, NMJ_ACTOR,\
	NMJ_DIRECTOR, NMJImage
from nmj.cleaners import TVShowCleaner
from nmj.scanners.tmdb import MediaNotFound
from nmj.utils import to_unicode
import pprint


_LOGGER = logging.getLogger(__name__)

class TTVDBScanner(TVShowScanner):
	def __init__(self):
		super(TTVDBScanner, self).__init__()
		self.web_api = Tvdb(
#			interactive=False,
#			select_first=False,
#			debug=True,
#			cache=True,
			banners=True,
#			actors=True,
#			custom_ui=self._get_custom_ui(),
			language="fr",
#			search_all_languages=False,
			apikey="5BA46DFDB0AB740E",
#			forceConnect=False
		)

	def get_fanarts(self, show):
		return [NMJImage(url) for url, _ in self.__get_images(show, "fanart")]

	def get_posters(self, show):
		return [NMJImage(url) for url, _ in self.__get_images(show, "poster")]

	def get_thumbnails(self, show):
		return [NMJImage(url) for _, url in self.__get_images(show, "poster")]

	def get_season_posters(self, show, season):
		_LOGGER.debug("Find season poster (%s)", season)
		return [NMJImage(url) for url, _ in self.__get_images(show, "season", season=season)]

	def get_season_thumbnails(self, show, season):
		return [NMJImage(url) for _, url in self.__get_images(show, "season", season=season)]

	def __retreive_image_infos(self, image_data):
		if int(image_data["ratingcount"]):
			rating = float(image_data["rating"])
		else:
			rating = 0
		full_url = image_data["_bannerpath"]
		thumb_url = image_data.get("_thumbnailpath", full_url)
		return (rating, full_url, thumb_url)

	def __get_images(self, show, *image_types, **kwargs):
		result = []
		#kwargs.update({"language" : ["fr", "en"]})
		try:
			for image_type in image_types:
				_LOGGER.debug("Image type (%s) : \n%s", image_type, pprint.pformat(show["_banners"][image_type]))
				for _, images in show["_banners"][image_type].iteritems():
					for _, image_data in images.iteritems():
						if kwargs:
							for key, value in kwargs.iteritems():
								if type(value) is list and image_data.get(key, None) in value:
									result.append(self.__retreive_image_infos(image_data))
								elif image_data.get(key, None) == value:
									result.append(self.__retreive_image_infos(image_data))
						else:
							result.append(self.__retreive_image_infos(image_data))

		except KeyError:
			pass
		result.sort(key=lambda x:x[0])
		result.reverse()
		return [(url, thumb) for (_, url, thumb) in result]

	def search(self, media):
		title = self.clean(media.title)
		for regexp in self.compiled_regexp:
			match = regexp.match(title)
			if match:
				params = match.groupdict()
				try:
					show = self.web_api[to_unicode(params.get("show_name", title))]
				except tvdb_shownotfound:
					raise MediaNotFound("No information found for %s", media)
				try:
					poster = self.get_posters(show)[0]
				except IndexError:
					poster = ""
				return [TVShowSearchResult(
					show["id"],
					poster,
					show["seriesname"],
					media.path,
					season=int(params.get("season", "1")),
					episode=int(params.get("episode", "1")),
					showdata=show,
				),]
		raise MediaNotFound("No information found for %s" % media)

	def get_details_from_media(self, media):
		title = self.clean(media.title)
		for pattern in self.accepted_regexp: #for regexp in self.compiled_regexp:
			_LOGGER.debug("test %s with regexp %s", title, pattern)
			regexp = re.compile(pattern)
			match = regexp.match(title)
			if match:
				_LOGGER.debug("regexp match!!")
				params = match.groupdict()
				for key, value in params.iteritems():
					params[key] = value.strip()
				return params
			else:
				_LOGGER.debug("regexp doesn't match!!")
		return {
			"show_name" : media.title,
			"season" : 1,
			"episode" : 1,
		}

	def get_default_details(self, media):
		details = self.get_details_from_media(media)
		return NMJTVMediaInfo(
			show=NMJTVShow(title=details.get("show_name", media.title), search_title=self.get_search_title(details.get("show_name", media.title))),
			season=NMJTVShowSeason(title="%s Saison %s" % (details.get("show_name", media.title), details.get("season", 1))),
			episode=NMJTVShowEpisode(title="%s episode s%se%s" % (details.get("show_name", media.title), details.get("season", 1), details.get("episode", 1))),
		)

	def get_details(self, search_result):
		show = search_result.showdata
		episode = search_result.showdata[search_result.season][search_result.episode]
		episode_title = episode.get("episodename", "Saison %s Episode %s" % (search_result.season, search_result.episode))
		str_actors = show["actors"].strip("|")
		main_actors = [NMJPerson(actor, NMJ_ACTOR) for actor in str_actors.split("|")]
		director = [NMJPerson(episode.get("director", ""), NMJ_DIRECTOR),]
		str_guests = episode.get("gueststars", None) or ""
		guests = [NMJPerson(actor, NMJ_ACTOR) for actor in str_guests.strip("|").split("|")]
		str_genres = show["genre"].strip("|")
		genres = str_genres.split("|")
		return NMJTVMediaInfo(
				show = NMJTVShow(
					ttid = show["imdb_id"],
					content_id = "tvdb%s" % show["id"],
					title=show["seriesname"],
					search_title=self.get_search_title(show["seriesname"]),
					release_date=datetime.datetime.strptime(show["firstaired"] or "9999-01-01", "%Y-%m-%d"),
					rating=show["rating"],
					posters=self.get_posters(show),
					thumbnails=self.get_thumbnails(show),
					wallpapers=self.get_fanarts(show),
					persons=main_actors + director,
					genres=genres,
					synopsis=show["overview"],
				),
				season = NMJTVShowSeason(
					ttid = show["imdb_id"],
					content_id = "tvdb%s" % show["id"],
					title = "%s Saison %s" % (show["seriesname"], search_result.season),
					rank = search_result.season,
					release_date=datetime.datetime.strptime(show["firstaired"] or "9999-01-01", "%Y-%m-%d"),
					rating=show["rating"],
					posters=self.get_season_posters(show, "%s" % search_result.season),
					thumbnails=self.get_season_thumbnails(show, "%s" % search_result.season),
					wallpapers=self.get_fanarts(show),
					persons=main_actors + director,
					genres=genres,
					synopsis=show["overview"],
				),
				episode = NMJTVShowEpisode(
					ttid=episode.get("imdb_id", search_result.search_id),
					content_id="tvdb%s" % episode.get("id", search_result.search_id),
					title = episode_title,
					rank = search_result.episode,
					search_title = self.get_search_title(episode_title),
					release_date=datetime.datetime.strptime(episode.get("firstaired", "9999-01-01") or "9999-01-01", "%Y-%m-%d"),
					rating=episode.get("rating", ""),
					synopsis=episode.get("overview", ""),
					persons=main_actors + guests + director,
					genres=genres,
					runtime=int(show["runtime"]) * 60,
				),
		)

	def clean(self, title):
		return TVShowCleaner().clean_title(title)

if __name__ == "__main__": # pragma: no cover
	from nmj.abstract import MediaFile

	logging.basicConfig(level=logging.DEBUG)
	scanner = TTVDBScanner()
	print scanner.search(MediaFile("Esprits Criminels s04e01.avi"))
	#scanner.get_details(MovieSearchResult(160320, "http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original/ejre3MX3Yf8vfjxjkhMV96nBJdp.jpg", "One Day...", "path"))
	result = scanner.get_details(scanner.search(MediaFile("Esprits Criminels s04e01.avi"))[0])

